<template>
    <div class="monaco-editor-wrapper">
        <div class="monaco-editor" ref="editorRef"></div>
        <div class="control-bar">
            <n-button size="medium" type="primary" @click="handleSave">
                保存
            </n-button>
        </div>
    </div>
</template>

<script setup lang="ts">
// https://github.com/vdesjs/vite-plugin-monaco-editor
import monakaiTheme from 'monaco-themes/themes/Monokai.json'
import { onMounted, ref, shallowRef, watch } from 'vue'
import { monaco } from './customMonaco'

const editorRef = ref<HTMLDivElement>()

interface IMonacoProps {
    value: string
    language: 'json'
}

const props = defineProps<IMonacoProps>()

const emit = defineEmits<{
    'update:value': [value: string]
    save: [value: string]
}>()

const monacoEditorIns = shallowRef<monaco.editor.IStandaloneCodeEditor>()

onMounted(() => {
    console.log('monakaiTheme======>', monakaiTheme)
    try {
        if (!editorRef.value) {
            return console.warn('editorRef container is null', editorRef)
        }
        const editorIns = monaco.editor.create(editorRef.value, {
            value: props.value,
            language: props.language,
        })

        monaco.editor.defineTheme(
            'monakai',
            monakaiTheme as monaco.editor.IStandaloneThemeData,
        )
        monaco.editor.setTheme('monakai')

        monacoEditorIns.value = editorIns

        editorIns.onDidChangeModelContent(() => {
            const value = editorIns.getValue()
            emit('update:value', value)
        })
    } catch (error) {
        console.warn(error)
    }
})

// watch(
//     () => props.value,
//     (n) => {
//         monacoEditorIns.value?.setValue(n)
//     },
//     {
//         flush: 'post',
//     },
// )

function handleSave() {
    const value = monacoEditorIns.value?.getValue()
    console.log('value======>', value)
    if (value) {
        emit('save', value)
    }
}
</script>

<style lang="scss" scoped>
.monaco-editor-wrapper {
    height: 100%;
    width: 100%;
    .monaco-editor {
        height: 100%;
        width: 100%;
    }
    .control-bar {
        position: absolute;
        bottom: 0;
        right: 0;
        background: none;
    }
}
</style>
